package com.ict.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.dto.IctProductDTO;
import com.ict.api.entity.IctProduct;
import com.ict.api.entity.IctSkuStock;
import com.ict.api.vo.IctProductVO;
import com.ict.api.vo.PageResult;
import com.ict.commons.exception.IctException;
import com.ict.mapper.IctProductMapper;
import com.ict.mapper.IctSkuStockMapper;
import com.ict.service.IctProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Slf4j
@Service
public class IctProductServiceImpl extends ServiceImpl<IctProductMapper, IctProduct> implements IctProductService {

    @Resource
    private IctProductMapper productMapper;

    @Resource
    private IctSkuStockMapper stockMapper;

    @Override
    public PageResult<IctProductVO> getProductList(IctProductDTO productDTO) {
        Page<IctProduct> page = new Page(productDTO.getPage(), productDTO.getPageSize());
        LambdaQueryWrapper<IctProduct> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(productDTO.getName()), IctProduct::getName, productDTO.getName());
        lqw.eq(productDTO.getProductCategoryId() != null, IctProduct::getProductCategoryId, productDTO.getProductCategoryId());
        lqw.gt(productDTO.getPriceMin() != null, IctProduct::getPrice, productDTO.getPriceMin());
        lqw.lt(productDTO.getPriceMax() != null, IctProduct::getPrice, productDTO.getPriceMax());
        productMapper.selectPage(page, lqw);
        List<IctProduct> records = page.getRecords();

        List<IctProductVO> list = new ArrayList<>();
        records.stream().forEach(item -> {
            IctProductVO ictProductVO = new IctProductVO();
            BeanUtils.copyProperties(item, ictProductVO);
            list.add(ictProductVO);
        });

        return new PageResult(productDTO.getPage(), productDTO.getPageSize(), page.getTotal(), list);
    }

    @Override
    public void addProduct(IctProductDTO productDTO) {
        productMapper.insert(productDTO);
    }

    @Override
    public Map<String, String> uploadProductImg(MultipartFile file, String imgFilepath) {
        try {
            //1. 获取原始文件名 , 切割出来后缀
            String filename = file.getOriginalFilename(); //   aa.jpg
            String extension = FilenameUtils.getExtension(filename); //jpg
//            String suffix = filename.substring(filename.lastIndexOf('.'));  //   .jpg

            //2. 构建一个新的文件名
            // 生成不带-的UUID字符串，类似于：b17f24ff026d40949c85a24f4f375d42
            String simpleUUID = IdUtil.simpleUUID();
            String newName = simpleUUID + "." +extension; //   69dd8caa24d641d28e0dcc313ad5d32a.jpg

            //3. 准备好保存的目录，确保这个目录是存在的
            String projectPath = System.getProperty("user.dir");
            File dir = new File(projectPath + imgFilepath);
            if(!dir.exists()){ //如果目录不存在
                dir.mkdirs();
            }

            //4. 保存文件
            File f = new File(projectPath + imgFilepath +newName);  // D:/heima123/69dd8caa24d641d28e0dcc313ad5d32a.jpg
            file.transferTo(f);

            //5. 返回结果（文件的名字）给页面
            Map<String, String> map = new HashMap<>();
            map.put("imgFilePath", newName);
            return map;
        } catch (IOException e) {
            log.error("upload img file error:{}", e.getMessage());
            throw new IctException("上传失败");
        }
    }

    @Override
    public void download(String name, String imgFilepath) {
        //1. 定位文件的位置
        String projectPath = System.getProperty("user.dir");
        File file = new File(projectPath + imgFilepath +  name);

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        //2 获取输入输出流对象

        try(FileInputStream fis = new FileInputStream(file);
            ServletOutputStream os = response.getOutputStream();
        ) {

            IOUtils.copy(fis , os);

        } catch (IOException e) {
            log.error("download img file error:{}", e.getMessage());
            throw new IctException("下载失败");
        }
    }

    @Override
    public void updateProductInfo(Long id, IctProductDTO productDTO) {
        productDTO.setId(id);
        productMapper.updateById(productDTO);
    }

    @Override
    public void deleteProduct(Long id) {
        productMapper.deleteById(id);

    }

    @Override
    public IctProductVO findProduct(Long id) {
        IctProduct ictProduct = productMapper.selectById(id);
        IctProductVO ictProductVO = new IctProductVO();
        BeanUtils.copyProperties(ictProduct, ictProductVO);
        IctSkuStock ictSkuStock = stockMapper.selectOne(new LambdaQueryWrapper<IctSkuStock>().eq(IctSkuStock::getProductId, ictProduct.getId()));
        BeanUtils.copyProperties(ictSkuStock, ictProductVO);
        return ictProductVO;
    }
}
